package com.hanggold.endpoint;

import com.hanggold.endpoint.bean.SourceBean;
import com.hanggold.endpoint.bean.TargetBean;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class BeanCopyApplication {

    private PropertyDescriptor propertyDescriptor;

    public static void main(String[] args) {

        TargetBean targetBean = new TargetBean();
        targetBean.setAge(1);
        targetBean.setBirthday(new Date());
        targetBean.setUsername("我是目标");

//        targetBean.getClass().get


        Map<String, PropertyDescriptor> targetMap = new HashMap<>(10);

        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(targetBean.getClass());



            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

            for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {

//                propertyDescriptor.getPropertyEditorClass()

                String name = propertyDescriptor.getName();

                System.out.printf("name = %s \n", name);

                targetMap.put(name, propertyDescriptor);

//              Method readMethod =  propertyDescriptor.getReadMethod();
//
//               Object obj =  readMethod.invoke(targetBean);
//
//                System.out.println("c: "+ obj);
//                Method writeMethod = propertyDescriptor.getWriteMethod();
//
//                System.out.println(writeMethod.getName());


//                propertyDescriptor.createPropertyEditor()


            }


            SourceBean sourceBean = new SourceBean();
            BeanInfo sourceBeanInfo = Introspector.getBeanInfo(sourceBean.getClass());

            PropertyDescriptor[] propertyDescriptors1 = sourceBeanInfo.getPropertyDescriptors();

            for (PropertyDescriptor propertyDescriptor : propertyDescriptors1) {

                Method method = propertyDescriptor.getWriteMethod();

//                method.getAnnotation()
                if (method != null) {

                    PropertyDescriptor targetP = targetMap.get(propertyDescriptor.getName());

                   Method readMethod =  targetP.getReadMethod();

                   Object value = readMethod.invoke(targetBean);

                    method.setAccessible(true);

                    method.invoke(sourceBean,new Object[]{value});

                }

            }

            System.out.println(sourceBean);

        } catch (Exception e) {
            e.printStackTrace();
        }


    }


}
